extends KinematicBody2D

signal died

export(float) var SPOT_RANGE = 350.0
export(float) var FOLLOW_RANGE = 700.0
export(float) var ATTACK_RANGE = 50.0
export(float) var MAX_FOLLOW_SPEED = 130
export(float) var ARRIVE_DISTANCE = 3.0
export(float) var SLOW_RADIUS = 150.0
export(float) var MASS = 1.4

var state = null

var has_target = false
var spawn_position = Vector2()
var target_position = Vector2()
var velocity = Vector2()

onready var animationPlayer = $AnimationPlayer
onready var animationTree = $AnimationTree
onready var animationState = animationTree.get("parameters/playback")


func _ready():
	add_to_group("enemy")
	#initiate_base_enemy()
	


func follow(vel, target_pos, max_speed):
	var desired_velocity = (target_pos - position).normalized() * max_speed
	var steering = (desired_velocity - vel) / MASS
	
	return vel + steering


func arrive_to(vel, target_pos, slow_radius, max_speed):
	var desired_velocity = (target_pos - position).normalized() * max_speed
	var distance_to_target = position.distance_to(target_pos)
	if distance_to_target < slow_radius:
		desired_velocity *= (distance_to_target / slow_radius) * 0.75 + 0.25
		
	var steering = (desired_velocity - vel) / MASS
	
	return vel + steering	


func take_damage(source, amount):
	if self.is_a_parent_of(source):
		return
	$Health.take_damage(amount)


func _on_target_positon_changed(new_position):
	target_position = new_position


func _on_Health_health_changed(new_health):
	print (new_health)
	if new_health == 0:
		emit_signal("died")


func kill():
	$Health.kill()
	

func initiate_base_enemy():
	spawn_position = position
	
	$Timer.connect("timeout", self, "_on_Timer_timeout")
	
	var target_node = get_tree().get_root().find_node("Player", true, false)
	if not target_node:
		print("Missing target node on %s" % get_path())
		return
	target_node.connect("position_changed", self, "_on_target_positon_changed")
	self.connect("died", self, "_on_target_died")	
	$Health.connect("health_changed", self, "_on_Health_health_changed")
	has_target = true
	animationTree.active = true



